package com.easy.common.util;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import com.easy.common.constant.SysProps;
import com.easy.common.util.Utility;

public class ServletUtility {
	private static List<String> needNoCheckUriList = new ArrayList();
	private static List<String> gbkCodeUriList = new ArrayList();

	public ServletUtility()
	{
	}

	public static void setNeedNoCheckUriList(String uriStr)
	{
		if (Utility.isNullorEmpty(uriStr))
			return;
		String uriList[] = uriStr.split(",");
		for (int i = 0; i < uriList.length; i++)
		{
			String uri = uriList[i].trim();
			if (!needNoCheckUriList.contains(uri))
				needNoCheckUriList.add(uri);
		}

	}

	public static void setNeedGbkCodeUriList(String uriStr)
	{
		if (Utility.isNullorEmpty(uriStr))
			return;
		String uriList[] = uriStr.split(",");
		for (int i = 0; i < uriList.length; i++)
		{
			String uri = uriList[i].trim();
			if (!gbkCodeUriList.contains(uri))
				gbkCodeUriList.add(uri);
		}

	}

	public static void resetNeedNoCheckUriList(String uriStr)
	{
		needNoCheckUriList.clear();
		setNeedNoCheckUriList(uriStr);
	}

	public static void resetNeedGBKCodeUriList(String uriStr)
	{
		gbkCodeUriList.clear();
		setNeedGbkCodeUriList(uriStr);
	}

	public static void forward(String toUrl, HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		RequestDispatcher requestDispatcher = request.getRequestDispatcher(toUrl);
		requestDispatcher.forward(request, response);
	}

	public static boolean isLoginAction(HttpServletRequest request)
	{
		if (request == null)
			return false;
		String qUri = request.getRequestURI();
		String contextPath = request.getContextPath();
		if (contextPath.equals(""))
			contextPath = "/mha";
		if (qUri.endsWith("/"))
			qUri = (new StringBuilder(String.valueOf(qUri))).append("index.jsp").toString();
		if (!qUri.startsWith(contextPath))
			qUri = (new StringBuilder(String.valueOf(contextPath))).append(qUri).toString();
		if (qUri.equals((new StringBuilder(String.valueOf(contextPath))).append("/login.jsp").toString()) || qUri.equals((new StringBuilder(String.valueOf(contextPath))).append("/index.jsp").toString()) || qUri.equals((new StringBuilder(String.valueOf(contextPath))).append("/logincheck.jsp").toString()) || qUri.equals((new StringBuilder(String.valueOf(contextPath))).append("/easy/inc/sessionerror.jsp").toString()) || qUri.equals((new StringBuilder(String.valueOf(contextPath))).append("/easy/inc/pagenevbar.jsp").toString()) || qUri.startsWith((new StringBuilder(String.valueOf(contextPath))).append("/com/easy/tech/system/act/MYSystemAct/").toString()) || qUri.startsWith((new StringBuilder(String.valueOf(contextPath))).append("/com/easy/tech/system/info/act/MYInfoAct/").toString()) || qUri.startsWith((new StringBuilder(String.valueOf(contextPath))).append("/easy/tech/system/info/").toString()))
			return true;
		if (!Utility.isNullorEmpty(SysProps.getString("NEED_NOT_CHECKED_URI")))
		{
			if (needNoCheckUriList.size() < 1)
				setNeedNoCheckUriList(SysProps.getString("NEED_NOT_CHECKED_URI"));
			for (int i = 0; i < needNoCheckUriList.size(); i++)
			{
				String uri = (String)needNoCheckUriList.get(i);
				if (qUri.startsWith((new StringBuilder(String.valueOf(contextPath))).append(uri).toString()))
					return true;
			}

		}
		return false;
	}

	public static boolean isGbkCode(HttpServletRequest request)
	{
		if (request == null)
			return false;
		if (gbkCodeUriList.size() > 0 || !Utility.isNullorEmpty(SysProps.getString("NEED_GBKCODE_URI")))
		{
			if (gbkCodeUriList.size() < 1)
				setNeedGbkCodeUriList(SysProps.getString("NEED_GBKCODE_URI"));
			String qUri = request.getRequestURI();
			String contextPath = request.getContextPath();
			if(!qUri.startsWith("http")){
				if (contextPath.equals(""))
					contextPath = "/mha";
				if (qUri.endsWith("/"))
					qUri = (new StringBuilder(String.valueOf(qUri))).append("index.jsp").toString();
				if (!qUri.startsWith(contextPath))
					qUri = (new StringBuilder(String.valueOf(contextPath))).append(qUri).toString();
			}
			
			for (int i = 0; i < gbkCodeUriList.size(); i++)
			{
				String uri = (String)gbkCodeUriList.get(i);
				if (qUri.startsWith((new StringBuilder(String.valueOf(contextPath))).append(uri).toString()))
					return true;
			}

		}
		return false;
	}

	public static boolean isValidSession(HttpSession session, String key)
	{
		if (session == null || key == null)
			return false;
		return session.getAttribute(key) != null;
	}

	public static String getCookieValue(HttpServletRequest request, String cookieName)
		throws Exception
	{
		return getCookieValue(request, cookieName, "");
	}

	public static String getCookieValue(HttpServletRequest request, String cookieName, String defaultValue)
		throws Exception
	{
		Cookie cookies[] = request.getCookies();
		return getCookieValue(cookies, cookieName, defaultValue);
	}

	public static String getCookieValue(Cookie cookies[], String cookieName, String defaultValue)
		throws Exception
	{
		if (cookies == null || cookieName == null)
			return null;
		for (int i = 0; i < cookies.length; i++)
		{
			Cookie cookie = cookies[i];
			if (cookieName.equals(cookie.getName()))
				return URLDecoder.decode(cookie.getValue(), "GBK");
		}

		return defaultValue;
	}

	public static void addCookie(String name, String value, int leafSeconds, HttpServletResponse response)
		throws Exception
	{
		Cookie cookie = new Cookie(name, URLEncoder.encode(value, "GBK"));
		cookie.setMaxAge(leafSeconds);
		response.addCookie(cookie);
	}

	public static Map getParamMap(HttpServletRequest request)
	{
		Map rtMap = new HashMap();
		Map paramMap = request.getParameterMap();
		for (Iterator iKeys = paramMap.keySet().iterator(); iKeys.hasNext();)
		{
			String key = (String)iKeys.next();
			String value[] = (String[])paramMap.get(key);
			if (value != null && value.length > 0)
				rtMap.put(key, value[0]);
			else
				rtMap.put(key, "");
		}

		return rtMap;
	}

	public static String getUrlParams(HttpServletRequest request)
		throws Exception
	{
		return getUrlParams(request, null);
	}

	public static String getUrlParams(HttpServletRequest request, ArrayList exKeyList)
		throws Exception
	{
		if (exKeyList == null)
			exKeyList = new ArrayList();
		StringBuffer params = new StringBuffer();
		for (Enumeration eParamName = request.getParameterNames(); eParamName.hasMoreElements();)
		{
			String paramName = (String)eParamName.nextElement();
			if (!exKeyList.contains(paramName))
			{
				String paramValue = Utility.iso88591ToGbk(request.getParameter(paramName));
				params.append(paramName);
				params.append("=");
				params.append(paramValue);
				params.append("&");
			}
		}

		if (params.length() > 1)
			params.delete(params.length() - 1, params.length());
		return params.toString();
	}

	public static Object applicationInstance(String className)
		throws ClassNotFoundException, IllegalAccessException, InstantiationException
	{
		return applicationClass(className).newInstance();
	}

	public static Class applicationClass(String className)
		throws ClassNotFoundException
	{
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (classLoader == null)classLoader = ServletUtility.class.getClassLoader();
		return classLoader.loadClass(className);
	}

	public static String getLocaleMsrg(ServletContext servletContext, HttpServletRequest request, String rscId, String msrg)
	{
		return "";
	}

	public static String getWebAppDir(ServletContext context)
	{
		return context.getRealPath("/");
	}

	public static String getWebAppDiskPart(ServletContext context)
	{
		return getWebAppDir(context).substring(0, 3);
	}

	public static String getParam(HttpServletRequest request, String paramName, String defalutValue)
	{
		String paramValue = null;
		Map paramMapInner = (Map)request.getAttribute("paramMapInner");
		if (paramMapInner != null)
		{
			paramValue = (String)paramMapInner.get(paramName);
			if (!Utility.isNullorEmpty(paramValue))
				return paramValue;
		}
		paramValue = request.getParameter(paramName);
		if (!Utility.isNullorEmpty(paramValue))
			return paramValue;
		paramValue = (String)request.getAttribute(paramName);
		if (!Utility.isNullorEmpty(paramValue))
			return paramValue;
		else
			return defalutValue;
	}

	public static String getParam(HttpServletRequest request, String paramName)
	{
		return getParam(request, paramName, "");
	}

}
